#!/bin/zsh

PHP_VERSION=82
PHP_FPM_PACKAGE_NAME=php${PHP_VERSION}-fpm
PHP_FPM_EXECUTABLE_NAME=php-fpm${PHP_VERSION}
PHP_FPM_LOGFILE=/var/log/php-fpm.log

function log () {
	echo $1 | /usr/bin/tee -a ${PHP_FPM_LOGFILE}
}

function error () {
	TEXT=$1
	echo ""${RED_STARGET}"$1"${RED_STOP}"" | /usr/bin/tee -a ${LOG_FILE}
}

function get_pid () {
	PATTERN=$1
	/bin/ps aux|/bin/grep "${PATTERN}" | /bin/sed '/grep/d'| /usr/bin/awk '{print $1}'
}

function install_php-fpm () {
	log "Installing ${PHP_FPM_PACKAGE_NAME}"
	package=`/sbin/apk list ${PHP_FPM_PACKAGE_NAME} 2>/dev/null`
	if [[ -z $package ]]; then
		/sbin/apk add --no-cache ${PHP_FPM_PACKAGE_NAME} php${PHP_VERSION}-xml php${PHP_VERSION}-session 2> /dev/null
	fi
	/bin/sed -i "s,;pid = run/php-fpm${PHP_VERSION}.pid,pid = run/php-fpm.pid,g" /etc/php${PHP_VERSION}/php-fpm.conf
	log "Installed ${PHP_FPM_PACKAGE_NAME}"
}

PHP_FPM_EXECUTABLE_PATH=`/usr/bin/which ${PHP_FPM_EXECUTABLE_NAME}`

PHP_FPM_PATTERN="{php-fpm${PHP_VERSION}} php-fpm: master process"
function get_pid_php-fpm () {
	PID=`get_pid ${PHP_FPM_PATTERN}`
	if [[ -f /var/run/php-fpm.pid ]]; then
		PID_FROM_FILE=`/bin/cat /var/run/php-fpm.pid`
		if [ ${PID} != ${PID_FROM_FILE} ]; then
			error "PID in file /var/run/php-fpm.pid is ${PID_FROM_FILE} != ${PID}"
			return 1
		fi
	fi
	echo ${PID}
}

function status_php-fpm () {
	PID=$(get_pid_php-fpm)
	if [ -z ${PID} ]; then
		echo -n "${PHP_FPM_EXECUTABLE_NAME} is not running: "
		echo "["${RED_START}"FAILED"${RED_STOP}"]"
		if [[ -z  ${PHP_FPM_EXECUTABLE_PATH} ]]; then
			log "${PHP_FPM_EXECUTABLE_NAME} not found in PATH. " 
			install_php-fpm
		fi
		return 1
	else
		log "${PHP_FPM_EXECUTABLE_NAME} is running with pid $(get_pid_php-fpm)"
		return 0
	fi
}

start_php-fpm () {
	echo -n "start php-fpm: "
	status_php-fpm > /dev/null
	PHP_FPM_NOT_RUNNING=$?
	if [ ${PHP_FPM_NOT_RUNNING} -eq 1 ]; then
		log "starting ${PHP_FPM_EXECUTABLE_NAME}"
		${PHP_FPM_EXECUTABLE_PATH}
	fi
	echo "[ "${GREEN_START}"OK"${GREEN_STOP}" ]"
}


main ()  {
	action=$1
	case $action in
		install)
			install_php-fpm 
			;;
		status)
			status_php-fpm 
			;;
		start)
			start_php-fpm
			;;
		*)
	esac
}

main $@

